#include<iostream>
#include<string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<string.h>
#include <unistd.h>

using namespace std;

const int PORT = 8081;

int main() {
    int client_fd;
    struct sockaddr_in server_addr;
    char buffer[1024];

    // 创建套接字
    if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    // 连接服务器
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(PORT);

    if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("connect");
        exit(1);
    }


// 输入用户名和密码
        string username, password;

        cout << "Please enter your username: ";
        cin >> username;

        cout << "Please enter your password: ";
        cin >> password;

        // 将用户名和密码发送到服务器
        sprintf(buffer, "%s %s", username.c_str(), password.c_str());
        send(client_fd, buffer, strlen(buffer), 0);
        read(client_fd, buffer, sizeof(buffer));
        cout << "Received: "<< buffer<< endl;
//        // 接收服务器的响应
//        int received = recv(client_fd, buffer, sizeof(buffer), 0);
//        cout << received << endl;
//        if (received > 0) {
//            buffer[received] = '\0';
//            cout << "Received: "<< buffer<< endl;
//        }
    // 如果登录成功，则与服务器进行通信
    if (strcmp(buffer, "Login successful") == 0) {
        while (1) {
            // 输入要发送的消息
            char inbuff[1024];
            cout << "Please enter a message to send: ";
            cin >> inbuff;
            getchar();

            // 将消息发送到服务器
            send(client_fd, inbuff, strlen(inbuff), 0);

            // 接收服务器的响应
            int received = recv(client_fd, inbuff, sizeof(inbuff), 0);
//            cout<< received<< endl;
            if (received > 0) {
                inbuff[received] = '\0';
                printf("Server Received:%s\n", inbuff);
            }
        }
    }

    // 关闭套接字
    close(client_fd);

    return 0;
}
